<?php

namespace app\api\controller;

use addons\wechat\library\Config as ConfigService;
use AlibabaCloud\SDK\Iot\V20180120\Iot;
use AlibabaCloud\SDK\Iot\V20180120\Models\PubRequest;
use app\admin\model\AssistantOrder;
use app\admin\model\Chargecode;
use app\admin\model\Cmdlog;
use app\admin\model\Devicelock;
use app\admin\model\Linedevice;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\shop\Withdraw;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdaytrade;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptableorder;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userwithdraw;
use app\admin\model\Voice;
use App\Api\PrinterService;
use App\Api\PrintService;
use app\api\service\AirService;
use app\api\service\BalanceService;
use app\api\service\DeviceService;
use app\api\service\FxVbillService;
use app\api\service\KdService;
use app\api\service\LockService;
use app\api\service\MpService;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\api\service\RoomService;
use app\api\service\TableService;
use app\api\service\VbillService;
use app\api\service\XhtMtService;
use app\common\controller\Api;
use App\Config\YlyConfig;
use App\Oauth\YlyOauthClient;
use Darabonba\OpenApi\Models\Config;
use EasyWeChat\Factory;
use fast\Http;
use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MQTTClient;
use think\Console;
use think\exception\HttpResponseException;
use think\Response;
use Workerman\Mqtt\Client;
use Workerman\Worker;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    protected $client;

    public function _initialize()
    {
        parent::_initialize();

        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => "LTAI5tRwpRY8GgGeFFUDhcpH",
            // 您的AccessKey Secret
            "accessKeySecret" => "JSHHCVXNruyCBlNKk1hPuFimiDAwmR"
        ]);
        // 访问的域名
        $config->endpoint = "iot.cn-shanghai.aliyuncs.com";
        $this->client = new  Iot($config);
    }

    /**
     * 首页
     *
     */
    public function index()
    {

        $shopChargeModel = new Shopcharge();
        $order = $shopChargeModel->where('order_no', "23020217140056499751575461")->find();
        $shopChargeModel->where('id', $order['id'])->update(['status' => 'payed']);
        $userBalanceModel = new Userbalance();
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
        $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'in', 'amount' => $charge['get_amount'], 'create_time' => time(),
            'shop_id' => $charge['shop_id'], 'order_id' => $order['id'], "mark" => "用户充" . $charge['amount'] . "得" . $charge['get_amount']]);
        $this->success('请求成功');
    }

    public function testRedis()
    {
        $uid = $this->request->param('user_id');
        $time = $this->request->param('time');
        $user_id = 25;
        $key = 'table_5';
        $cache = $this->redis->get($key);
        if($cache){
            if($uid != $cache){
                $this->error('已经有顾客在支付，请稍后再试');
            }
        }else{
            $this->redis->set($key, $user_id, $time);
        }

        $this->success('写入成功');

    }

    public function getHour()
    {

        $hour = array();

        for ($i = 0; $i <= 24; $i++) {
            $d = strtotime("+" . $i . " hours");
            $hour [] = date("G", $d);
        }
        $this->success('', $hour);
    }

    public function getFiveDate()
    {


        $date = array();
        $weekarray = array("日", "一", "二", "三", "四", "五", "六");
        for ($i = 0; $i <= 4; $i++) {
            $d = strtotime("+" . $i . " day");
            $obj = array();
            $obj['date'] = date("m.d", $d);
            if ($i == 0) {
                $obj['week'] = "今天";
            } else {
                $obj['week'] = "周" . $weekarray[date("w", $d)];
            }
            $date[] = $obj;
        }
        $this->success('', $date);

    }

    public function getHourTime()
    {


        $new = getTimeList();

        $this->success("", $new);

    }

    public function test2()
    {


        $d = date("w", time());
        $this->success('', $d);


    }

    public function test3()
    {
        $out_trade_no = "23021412275810151505130060";
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
        $shopOrderModel->where('id', $order['id'])->update(['status' => 'doing', 'update_time' => time()]);

        $this->redis->set($order['shop_id'], time());
        $shopRoomBookModel = new Shoproombook();
        $db = array();
        $db['user_id'] = $order['user_id'];
        $db['room_id'] = $order['room_id'];
        $db['shop_id'] = $order['shop_id'];
        $db['order_id'] = $order['id'];
        $db['start_time'] = $order['book_start'];
        $db['end_time'] = $order['book_end'];
        $db['status'] = 'doing';
        $db['type'] = 'working';
        $book_id = $shopRoomBookModel->insertGetId($db);


        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['room_id'])->find();
        $orderModel = new Shoporder();
        $order = $orderModel->where('id', $order['id'])->find();
        $orderNo = $order['order_no'];
        $minute = floor(($db['end_time'] - time()) % 86400 / 60);
        $sn = $device['sn'];


        if ($device) {

            if ($device['status'] != 'online') {
                $this->error("设备没在线，请联系客服");
            }
            $req = array();
            $req['sec'] = $minute * 60;
            $req['orderNo'] = $orderNo;
            $req['sn'] = $sn;
            error_log("====cmd ret===" . json_encode($req));


            $ret = http_post_json($this->openCmdUrl, json_encode($req));

            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $this->success('');

    }

    public function testOrder()
    {

        $out_trade_no = "23022511195357985099923422";

        $shopChargeModel = new Shopcharge();
        $order = $shopChargeModel->where('order_no', $out_trade_no)->find();
        $shopChargeModel->where('id', $order['id'])->update(['status' => 'payed']);
        $userBalanceModel = new Userbalance();
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
        $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'in', 'amount' => $charge['get_amount'], 'create_time' => time(),
            'shop_id' => $charge['shop_id'], 'order_id' => $order['id'], "mark" => "用户充" . $charge['amount'] . "得" . $charge['get_amount']]);

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $charge['shop_id'])->find();


        /**
         * 商家分润
         */
        $shopOrderProfitModel = new Shoporderprofit();
        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
            'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['amount'] - $order['rate'] - $order['pay_rate']))]);


        $this->success('成功');
    }

    public function test4()
    {

        $out_trade_no = "23030910385850555110934791";
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
        $shopOrderModel->where('id', $order['id'])->update(['status' => 'payed', 'update_time' => time()]);


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();

        /**
         * 商家分润
         */
        $shopOrderProfitModel = new Shoporderprofit();
        $shopAgentProfitModel = new Userorderprofit();
        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
            'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['pay_amount'] - $order['rate'] - $order['pay_rate']))]);

        /**
         * 代理商分润
         */
        if ($shop['agent_ratio'] > 0) {

            $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;
            $shopAgentProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
        }


        $this->redis->set($order['shop_id'], time());

        $bookModel = new Shoproombook();
        $deviceService = new DeviceService();

        $roomService = new RoomService();
        $roomService->addBookData($order);

        $this->success('');
    }

    public function addLine()
    {

        $device = new Linedevice();
        $list = [];
        for ($i = 1; $i <= 300; $i++) {
            $obj = array();
            $obj['create_time'] = time();
            $var = sprintf("L%08d", $i);
            $obj['device_no'] = $var;
            if ($i <= 100) {
                $obj['org_id'] = -1;
                $obj['url'] = "http://line.qhy.51fxyf.com/" . $var;

            } else {
                $obj['org_id'] = 1;
                $obj['device_no'] = $var;
                $obj['url'] = "http://line.xht.aiqps.cn/" . $var;

            }
            $list[] = $obj;
        }
        $device->insertAll($list);

    }

    public function test()
    {

        $out_trade_no = "23031610404398505255090129";
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
        $shopOrderModel->where('id', $order['id'])->update(['status' => 'payed', 'update_time' => time()]);


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();

        /**
         * 商家分润
         */
        $shopOrderProfitModel = new Shoporderprofit();
        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
            'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['pay_amount'] - $order['rate'] - $order['pay_rate']))]);

        /**
         * 代理商分润
         */
        if ($shop['agent_ratio'] > 0) {

            $userOrderProfitModel = new Userorderprofit();

            $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;

            if ($agentFee > 0) {
                $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                    'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
            }

        }


        $this->redis->set($order['shop_id'], time());


        $roomService = new RoomService();
        $roomService->addBookData($order);

        $this->success('成功');

    }

    public function testBalance(BalanceService $balanceService)
    {
        $balance = $balanceService->shopBalance(3);
        $this->success('', $balance);

    }

    public function token()
    {


        $mtReq = array();
        $mtReq['shop_id'] = 1;
        $mtReq['code'] = "4935001199";
        $mtService = new MtService();
        $mtInfo = $mtService->couponInfo($mtReq);
        $this->success('', $mtInfo);
    }

    public function testUpdate()
    {
        $roomSetModel = new Shoproomset();
        $list = $roomSetModel->select();
        $roomModel = new Shoproom();
        foreach ($list as $key => $val) {
            $room = $roomModel->where('id', $val['room_id'])->find();
            $roomSetModel->where('id', $val['id'])->update(['shop_id' => $room['shop_id']]);
        }
        $this->success("成功");
    }

    public function testF()
    {
        $mtService = new MtService();
        $ischeck = $mtService->test();
        $this->success('', $ischeck);
    }

    public function testVbillFile()
    {

        $date = $this->request->param('date');
        $type = $this->request->param('type');
        $req = array();
        $req['billDate'] = $date;
        $req['billType'] = $type;
        $vbillService = new VbillService();
        $result = $vbillService->getFileUrl($req);
        $this->success('', json_decode($result));

    }

    public function testAmount()
    {
        $amount = 52.00;
        $pay_rate = formatMoney(0.6 * $amount / 100);
        $price = $amount - $pay_rate;
        $rate = formatMoney(5 * $price / 100);


        $profit = $amount - $rate - $pay_rate;


        $realPay = formatMoney($amount - $amount * 0.006);
        $allotValue = formatMoney(95 * $realPay / 100);
        $ret = array();
        $ret['profit'] = formatMoney($profit);
        $ret['allot'] = $allotValue;


        $this->success('', $ret);
    }

    public function testAmount2()
    {

        $pay_price = 918.1;
        $realPay = bcsub($pay_price, $pay_price * 0.006, 2);
        $shopProfit = bcdiv(((100 - 3) * $realPay), 100, 2);


        $this->success('', $shopProfit);
    }

    public function testAmount3()
    {

        $pay_price = $this->request->param('amount');
        $realPay = bcsub($pay_price, formatMoney($pay_price * 0.006), 2);
        $shopProfit = bcdiv(((100 - 3) * $realPay), 100, 2);


        $this->success('', $shopProfit);
    }

    public function testLock2()
    {

        $deviceLockModel = new Devicelock();
        $lock = $deviceLockModel->where('room_id', 281)->find();

        error_log("==test=lock===" . json_encode($lock));

        if ($lock) {
            if ($lock['is_gateway'] == 1) {
                //网关开锁
                $lockService = new LockService();
                $lockReq = array();
                $lockReq['lockId'] = $lock['lockId'];
                $lockService->openLock($lockReq);

            }
        }

        $this->success('测试');

    }

    public function testAdd()
    {

        $key = $this->request->param('key');
        $flag = $this->request->param('flag');
        for ($i = 1; $i <= 15; $i++) {
            $lock = $this->redis->get($key, 0);
            if ($lock == 0) {
                $this->redis->set($key, 1, 30);
                break;
            }
            error_log($flag . "====lock=======" . $lock . "==========");
            if ($i == 15) {
                $this->error("提交订单失败");
            }
            sleep(1);
        }
        //生成订单
        sleep(4);
        $this->redis->rm($key);
        $this->success('订单生成成功' . $flag);

    }

    public function testLock()
    {

        $t = $this->redis->getLock("test");
        $this->success($t);
    }

    public function testLock3()
    {

        $this->redis->rmLock("test");
        $this->success();
    }

    public function testDate()
    {

        $d1 = "2023-08-28";

        $time = strtotime($d1);

        if ($time < time()) {

            $d = date("Y-m-d", time());
            $this->success($d);
        } else {
            $this->success($d1);
        }
    }

    public function testMsg()
    {

        $obj = array();
        $obj['openid'] = "obLIl6WpfZf8TKWWTsWXCIwBA3RU";
        $obj['room'] = "开心玩";
        $obj['amount'] = "10";
        $obj['phone'] = "18201753497";
        $obj['time'] = date("Y-m-d", time());
        $obj['endTime'] = date("Y-m-d", time());


        $mpService = new MpService();
        $mpService->addOrderNotify($this->wxApp, $obj);
        $this->success('成功');
    }

    public function testMsg2()
    {

        $obj = array();
        $obj['openid'] = "obLIl6WpfZf8TKWWTsWXCIwBA3RU";
        $obj['room'] = "开心玩";
        $obj['name'] = "18201753497";
        $obj['time'] = date("Y-m-d", time());


        $mpService = new MpService();
        $mpService->doneOrderNotify($this->wxApp, $obj);
        $this->success('成功');
    }

    public function testMsg3()
    {

        $obj = array();
        $obj['openid'] = "obLIl6WpfZf8TKWWTsWXCIwBA3RU";
        $obj['shop'] = "雀和友";
        $obj['room'] = "开心玩";
        $obj['time1'] = date("Y-m-d h:i", time());
        $obj['time2'] = date("Y-m-d h:i", time());


        $mpService = new MpService();
        $mpService->cleanStartNotify($this->wxApp, $obj);
        $this->success('成功');
    }

    public function testMsg4()
    {

        $obj = array();
        $obj['openid'] = "obLIl6WpfZf8TKWWTsWXCIwBA3RU";
        $obj['shop'] = "雀和友";
        $obj['room'] = "开心玩";


        $mpService = new MpService();
        $mpService->cleanDoneNotify($this->wxApp, $obj);
        $this->success('成功');
    }

    public function testMsg5()
    {

        $obj = array();
        $obj['openid'] = "obLIl6WpfZf8TKWWTsWXCIwBA3RU";
        $obj['device'] = "8734335435";
        $obj['shop'] = "雀和友";
        $obj['time'] = date("Y-m-d h:i");


        $mpService = new MpService();
        $mpService->offlineNotify($this->wxApp, $obj);
        $this->success('成功');
    }

    public function test6()
    {

        $time = strtotime("2023-09-03 17:04:00");
        $day = date("w", $time);
        $this->success('', $day);

    }

    public function test7()
    {

        $shopChargeModel = new Shopcharge();
        $order = $shopChargeModel->where('order_no', "23090411144553535597566309")->find();
        $shopChargeModel->where('id', $order['id'])->update(['status' => 'payed']);
        $userBalanceModel = new Userbalance();
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
        $balance = $userBalanceModel->where('b_type', 'charge')->where('order_id', $order['id'])->find();
        if (!$balance) {
            $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'in', 'amount' => $charge['get_amount'], 'create_time' => time(),
                'shop_id' => $charge['shop_id'], 'order_id' => $order['id'], "mark" => "用户充" . $charge['amount'] . "得" . $charge['get_amount']]);

            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $charge['shop_id'])->find();


            /**
             * 商家分润
             */
            $pay_price = $order['amount'];
            $realPay = formatMoney($pay_price - $pay_price * 0.006);
            $shopProfit = formatMoney((100 - $shop['ratio']) * $realPay / 100);
            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => $shopProfit]);


            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();
                $agentFee = $shop['agent_ratio'] * $order['amount'] / 100;
                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }


            }
        }
        $this->success('成功');
    }

    public function test8()
    {

        $user_id = 1264;
        $roomBookModel = new Shoproombook();
        $book = $roomBookModel->where('status', 'in', ['doing', 'done'])->
        where('user_id', $user_id)->order('end_time', 'desc')->find();

        $this->success('', $book);
    }

    public function testPrint()
    {
        $config = new YlyConfig('1086371393', 'b7b301bb9d18437eaebc9304e04295ed');
        $config->setRequestUrl('https://open-api.10ss.net/v2');
        $client = new YlyOauthClient($config);
        $token = $client->getToken();   //若是开放型应用请传授权码code
        $print = new PrintService($token->access_token, $config);

        $machine_code = "4004849939";               //商户授权机器码
        $origin_id = getOrderSn();
        /**文本接口开始**/
//58mm排版 排版指令详情请看 http://doc2.10ss.net/332006
        $content = "<FS2><center>**#1 雀和友总部店**</center></FS2>";
        $content .= str_repeat('.', 32);
        $content .= "<FS2><center>--在线支付--</center></FS2>";
        $content .= "<FS><center>雀和友总部店</center></FS>";
        $content .= "订单时间:" . date("Y-m-d H:i") . "\n";
        $content .= "订单编号:40807050607030\n";
        $content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
        $content .= "<table>";
        $content .= "<tr><td>烤土豆(超级辣)</td><td>x3</td><td>5.96</td></tr>";
        $content .= "<tr><td>烤豆干(超级辣)</td><td>x2</td><td>3.88</td></tr>";
        $content .= "<tr><td>烤鸡翅(超级辣)</td><td>x3</td><td>17.96</td></tr>";
        $content .= "<tr><td>烤排骨(香辣)</td><td>x3</td><td>12.44</td></tr>";
        $content .= "<tr><td>烤韭菜(超级辣)</td><td>x3</td><td>8.96</td></tr>";
        $content .= "</table>";
        $content .= str_repeat('.', 32);
        $content .= "<QR>这是二维码内容</QR>";
        $content .= "小计:￥82\n";
        $content .= "折扣:￥４ \n";
        $content .= str_repeat('*', 32);
        $content .= "订单总价:￥78 \n";
        $content .= "<FS2><center>**#1 完**</center></FS2>";

        try {
            var_dump($print->index($machine_code, $content, $origin_id));
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function testData()
    {
        $url = "https://open.ys7.com/api/lapp/token/get";
        $req = array();
        $req['appKey'] = "661a7bc3b2f2495482f5e76025bbe08d";
        $req['appSecret'] = "d52010862c6060e0110072a5eb53741a";

        $result = Http::post($url, $req);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            $token = $result['data']['accessToken'];
            $expireTime = $result['data']['expireTime'];

            $time = strtotime("-30 minute");
            $startDate = date("Y-m-d H:i:s", $time) . '.123'; // 指定日期
            $startTimestamp = (float)sprintf('%.0f', strtotime($startDate) * 1000 + explode(' ', microtime())[0] * 1000);

        }
        $this->success('', $result);
    }

    public function shareCode()
    {
        $config = get_addon_config('qrcode');
        if (isset($config['limitreferer']) && $config['limitreferer']) {
            $referer = $this->request->server('HTTP_REFERER', '');
            $refererInfo = parse_url($referer);
            $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
            $refererHostArr = explode('.', $refererHost);
            $wildcardDomain = '';
            if (count($refererHostArr) > 2) {
                $refererHostArr[0] = '*';
                $wildcardDomain = implode('.', $refererHostArr);
            }
            $allowRefererList = $config['allowrefererlist'] ?? '';
            $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
            $domainArr = array_filter(array_unique($domainArr));
            $domainArr[] = request()->host(true);

            $inAllowList = false;

            if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
                $inAllowList = true;
            }

            if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
                $inAllowList = true;
            }

            if (!$inAllowList) {
                $response = Response::create('暂无权限', 'html', 403);
                throw new HttpResponseException($response);
            }
        }
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));


        for ($i = 1; $i <= 100; $i++) {
            $sn = 9100 + $i;
            $url = "http://share.scan.qhy.51fxyf.com/" . $sn;
            $params['text'] = $url;
            $params['label'] = $sn;

            $qrCode = \addons\qrcode\library\Service::qrcode($params);

            $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

            $response = Response::create()->header("Content-Type", $mimetype);

            // 直接显示二维码
            header('Content-Type: ' . $qrCode->getContentType());
            $response->content($qrCode->writeString());

            // 写入到文件
            if ($config['writefile']) {
                $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
                if (!is_dir($qrcodePath)) {
                    @mkdir($qrcodePath);
                }
                if (is_really_writable($qrcodePath)) {
                    $filePath = $qrcodePath . $sn . '.' . $config['format'];
                    $qrCode->writeFile($filePath);
                }
            }
        }


        $this->success('成功');


    }

    public function allOrderRefund()
    {
        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');

        $orgModel = new Org();
        $org = $orgModel->where('id', 27)->find();
        $mno = $org['mno'];//获取雀侠商户号

        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $order_no;
        $req['amt'] = $amount;

        error_log("=APP=refund req===" . json_encode($req));
        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        error_log("==APP===refund=sxf==" . $ret);
        $result = json_decode($ret, true);

        //判断原订单不一致的问题
        if ($result['code'] != '0000') {
            $this->error($result['msg']);
        }
        //判断订单是否退款成功
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        $this->success('',$result);
    }

    public function allOrderRefund2()
    {
        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');

        $orgModel = new Org();
        $org = $orgModel->where('id', 27)->find();
        $mno = $org['mno'];//获取雀侠商户号

        $req = array();
        $req['mno'] = 399230630431837;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $order_no;
        $req['amt'] = $amount;

        error_log("=APP=refund req===" . json_encode($req));
        $vbillService = new FxVbillService();
        $ret = $vbillService->refund($req);
        error_log("==APP===refund=sxf==" . $ret);
        $result = json_decode($ret, true);

        //判断原订单不一致的问题
        if ($result['code'] != '0000') {
            $this->error($result['msg']);
        }
        //判断订单是否退款成功
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        $this->success('成功');
    }

    public function refundTableOrder()
    {
        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();


        $shopMnoModel = new Shopmno();
        $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();
        $mno = $org['mno'];//纷享未来药房

        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $order['order_no'];
        $req['amt'] = $amount;


        error_log("==refund req===" . json_encode($req));
        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        error_log("=====refund=sxf==" . $ret);
        $result = json_decode($ret, true);
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        if ($order['is_allot'] == 1) {
            //重新分账
        }

//        $deviceModel = new Shopdevice();
//        $device = $deviceModel->where('shop_id',$order['shop_id'])->where('room_id',$order['table_id'])->where('device_type','tq')->find();
//
//        $req = array();
//        $req['switchOne'] = 1;
//        $req['switchTwo'] = 1;
//        $req['door'] = 2;
//        $req['hello'] = "欢迎下次来玩";
//        $req['orderNo'] = $order['order_no'];
//        $req['sn'] = $device['sn'];
//
//        $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
//        $ret = json_decode($ret, true);
//        if ($ret['code'] == 0) {
//            $msg = "正在打开中";
//        }
//
//        $cmdModel = new Cmdlog();
//        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);


        $this->success('成功', $result);
    }

    public function testMjRefund()
    {
        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');
        $tableOrderModel = new Shoporder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();


        $shopMnoModel = new Shopmno();
        $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();
        $mno = $org['mno'];//纷享未来药房
        if ($shopMno && $shopMno['ratio'] == 100) {
            $mno = $shopMno['mno'];
        }
        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $order['order_no'];
        $req['amt'] = $amount;


        error_log("==refund req===" . json_encode($req));
        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        $this->success('', $ret);
        error_log("=====refund=sxf==" . $ret);
        $result = json_decode($ret, true);
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        if ($order['is_allot'] == 1) {
            //重新分账
        }

//        $deviceModel = new Shopdevice();
//        $device = $deviceModel->where('shop_id',$order['shop_id'])->where('room_id',$order['table_id'])->where('device_type','tq')->find();
//
//        $req = array();
//        $req['switchOne'] = 1;
//        $req['switchTwo'] = 1;
//        $req['door'] = 2;
//        $req['hello'] = "欢迎下次来玩";
//        $req['orderNo'] = $order['order_no'];
//        $req['sn'] = $device['sn'];
//
//        $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
//        $ret = json_decode($ret, true);
//        if ($ret['code'] == 0) {
//            $msg = "正在打开中";
//        }
//
//        $cmdModel = new Cmdlog();
//        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);


        $this->success('成功');
    }

    public function assistantOrderRefund()
    {
        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');
        if (empty($order_no)) {
            $this->error('需要传入订单编号');
        }

        $assistangtOrderModel = new AssistantOrder();
        $order = $assistangtOrderModel->where('order_no', $order_no)->find();
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order['status'] == 'refund') {
            $this->error('该订单已退款,无需重复操作');
        }
        $mno = '399250226672285';//雀侠商户号

        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $order['order_no'];
        $req['amt'] = $amount;
        error_log("==refund req===" . json_encode($req));

        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        error_log("=====refund=sxf==" . $ret);

        $result = json_decode($ret, true);
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }

        // 退款成功，修改订单状态
        $assistangtOrderModel->where('order_no', $order_no)->update(['status' => 'refund']);
        $this->success('');

    }

    public function testPrice()
    {

        $startTime = "2023-12-31 21:01";
        $endTime = "2023-12-31 21:52";


        $str = '{"time1":"17:00~09:00","price1":"26.8","time2":"09:00~17:00","price2":"23.8"}';


        //$this->success('',intval("09"));
        $rule = json_decode($str, true);
        $startTime1 = explode("~", $rule['time1'])[0];
        $endTime1 = explode("~", $rule['time1'])[1];

        $startTime2 = explode("~", $rule['time2'])[0];
        $endTime2 = explode("~", $rule['time2'])[1];


        $startTime1 = intval($startTime1);
        $endTime1 = intval($endTime1);


        $startTime2 = intval($startTime2);
        $endTime2 = intval($endTime2);
        $slots = array();

        if ($endTime1 < $startTime1) {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
        }

        if ($endTime2 < $startTime2) {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
        }
        $start = date("H", strtotime($startTime));

        $minute = floor((strtotime($endTime) - strtotime($startTime)) % 86400 / 60);
        echo $minute . "\n";
        $hour = floor($minute / 60);

        $amount = get_charge($start, $hour, $slots, $minute);

        //echo $hour."====amount====".$amount."======".json_encode($slots);


        echo $amount;


        //$this->success('',$ret);

    }

    function get_charge($starttime, $proctime, $slots, $minute)
    {


        if ($proctime < 1) $proctime = 1;
        $min = $minute - $proctime * 60;
        $lastMoney = 0;

        $charge = 0;
        for ($i = 0; $i < $proctime; $i += 1) {
            $time = ($starttime + $i) % 24;
            foreach ($slots as $slot) {
                if ($slot["begin"] <= $time && $time < $slot["end"]) {
                    $charge += $slot["charge"];
                    $lastMoney = $slot['charge'];
                    //echo $charge."======".$time."\n";
                }
            }
        }

        $charge += $min * $lastMoney / 60;

        return round($charge, 2);
    }

    public function testVoice()
    {

        $cArray = array();
        $cArray['cmd'] = "voice";
        $cArray['msg'] = "A07台只剩下15分钟，尽快续费";
        $pubRequest = new PubRequest([
            "productKey" => "ggy1jAcSplM",
            "topicFullName" => "/ggy1jAcSplM/" . "FPD80000101935" . "/user/get",
            "messageContent" => base64_encode(json_encode($cArray)),
            "iotInstanceId" => "iot-06z00htbh8lvvfe"

        ]);
        $resp = $this->client->pub($pubRequest);

        $this->success('成功');
    }

    public function removeKey()
    {
        $id = $this->request->param('id');

        $this->redis->rm($id);

        $this->success('成功');
    }

    public function testCmd()
    {


        $req = array();
        $deviceService = new DeviceService();
        $result = $deviceService->dxIot($req);
        $result = json_decode($result, true);
        $code = $result['code'];
        if ($code == 0) {
            $this->success("成功");
        }

    }

    public function testTq()
    {


        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();


        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $order['table_id'])->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();
        $rule = json_decode($table['rule'], true);
        $book_end = $order['book_end'];
        $minute = floor(($book_end - $order['book_start']) % 86400 / 60);
        $start = date("H", $order['book_start']);


        $startTime1 = explode("~", $rule['time1'])[0];
        $endTime1 = explode("~", $rule['time1'])[1];

        $startTime2 = explode("~", $rule['time2'])[0];
        $endTime2 = explode("~", $rule['time2'])[1];


        $startTime1 = intval($startTime1);
        $endTime1 = intval($endTime1);


        $startTime2 = intval($startTime2);
        $endTime2 = intval($endTime2);
        $slots = array();

        if ($endTime1 < $startTime1) {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
        }

        if ($endTime2 < $startTime2) {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
        }


        $hour = floor($minute / 60);
        $amount = get_charge($start, $hour, $slots, $minute);

        if ($amount <= $table['min_amount']) {
            $amount = $table['min_amount'];
        }

        if ($amount > $order['ya_amount'] && $order['pay_amount'] > 0) {
            $amount = $order['ya_amount'];//先暂时这样处理
        }

        $orderAmount = $order['pay_amount'];


        //2.断电

        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();
        $mno = $org['mno'];//纷享未来药房

        echo $orderAmount;
        if ($orderAmount > 0) {
            $userBalanceModel = new Userbalance();
            $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
            $refundAmount = 0;
            if ($balance == 0) {
                //3. 发分润
                $pay_rate = formatMoney($shop['pay_rate'] * $amount / 100);
                $rate = formatMoney($shop['ratio'] * $amount / 100);
                $shopProfit = $amount - $pay_rate - $rate;
                $refundAmount = $orderAmount - $amount;

                echo "=====分润======" . $shopProfit;
            } else {

                if ($amount <= $balance) {
                    $refundAmount = $orderAmount;
                    $dbBalance = $amount;
                } else {
                    $refundAmount = $orderAmount - ($amount - $balance);
                    $dbBalance = $balance;
                }
                echo "========2==========";

            }
            //部分退款

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
            if ($shopMno) {
                $mno = $shopMno['mno'];
            }
            $req = array();
            $req['mno'] = $mno;
            $req['ordNo'] = getOrderSn();
            $req['origOrderNo'] = $order['order_no'];
            $req['amt'] = formatMoney($refundAmount);

            $this->success('', $req);
        } else {
            $this->success('', "=====2===");

        }
    }

    public function testRefundCharge()
    {

        $amount = $this->request->param('amount');
        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shopcharge();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();


        $shopMnoModel = new Shopmno();
        $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
        $orgModel = new Org();
        $org = $orgModel->where('id', $order['org_id'])->find();
        $mno = $org['mno'];//纷享未来药房
        if ($shopMno && $shopMno['ratio'] == 100) {
            $mno = $shopMno['mno'];
        }
        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $order['order_no'];
        $req['amt'] = $amount;


        error_log("==refund req===" . json_encode($req));
        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        $this->success('', $ret);
        error_log("=====refund=sxf==" . $ret);
        $result = json_decode($ret, true);
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        if ($order['is_allot'] == 1) {
            //重新分账
        }

//        $deviceModel = new Shopdevice();
//        $device = $deviceModel->where('shop_id',$order['shop_id'])->where('room_id',$order['table_id'])->where('device_type','tq')->find();
//
//        $req = array();
//        $req['switchOne'] = 1;
//        $req['switchTwo'] = 1;
//        $req['door'] = 2;
//        $req['hello'] = "欢迎下次来玩";
//        $req['orderNo'] = $order['order_no'];
//        $req['sn'] = $device['sn'];
//
//        $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
//        $ret = json_decode($ret, true);
//        if ($ret['code'] == 0) {
//            $msg = "正在打开中";
//        }
//
//        $cmdModel = new Cmdlog();
//        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);


        $this->success('成功');
    }

    public function testCancelMt()
    {

        $array = array();
        $array['id'] = 296;
        $array['deal_id'] = 1220810637;
        $array['code'] = 9322675320;


        $xhtService = new XhtMtService();
        $result = $xhtService->canceCoupon($array);

        $this->success('', $result);
    }

    public function test10()
    {

        $id = $this->request->param('id');

        $shopModel = new Shop();
        $list = $shopModel->where('org_id', 'in', [27, 53])->select();
        $roomModel = new Shoproom();
        foreach ($list as $key => $val) {

            $roomList = $roomModel->where('shop_id', $val['id'])->select();
            foreach ($roomList as $k => $v) {
                $cacheKey = "room_" . $v['id'];
                $this->redis->rm($cacheKey);

            }
        }
        $this->success('成功');

    }

    public function testMtToken()
    {
        $req = array();
        $req['shop_id'] = 114;
        $mtService = new MtService();
        $result = $mtService->refreshToken($req);

        $this->success('', $result);
    }

    public function overOrder()
    {

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $from = $this->request->param('from');

        if ($order['status'] == 'done') {

            $this->error("此订单此完成 无需操作");
        }


        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        if ($from != 'task') {
            if (($order['is_qiu'] == -1 || $order['is_lock'] == -1) && $device['is_weight'] == 1) {

                $this->error("", "", "2");
            }
        }
        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $order['table_id'])->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();
        $rule = json_decode($table['rule'], true);
        $book_end = time();
        $minute = floor(($book_end - $order['book_start']) % 86400 / 60);
        $hour = ceil($minute / 60);
        $start = date("H", $order['book_start']);


        $startTime1 = explode("~", $rule['time1'])[0];
        $endTime1 = explode("~", $rule['time1'])[1];

        $startTime2 = explode("~", $rule['time2'])[0];
        $endTime2 = explode("~", $rule['time2'])[1];


        $startTime1 = intval($startTime1);
        $endTime1 = intval($endTime1);


        $startTime2 = intval($startTime2);
        $endTime2 = intval($endTime2);
        $slots = array();

        if ($endTime1 < $startTime1) {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime1;
            $obj['end'] = $endTime1;
            $obj['charge'] = $rule['price1'];
            $slots[] = $obj;
        }

        if ($endTime2 < $startTime2) {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = 24;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
            $obj = array();
            $obj['begin'] = 0;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;

        } else {
            $obj = array();
            $obj['begin'] = $startTime2;
            $obj['end'] = $endTime2;
            $obj['charge'] = $rule['price2'];
            $slots[] = $obj;
        }

        $hour = floor($minute / 60);

        $orderAmount = $order['pay_amount'];
        $pay_amount = 0;
        if ($order['mt_code'] != '' || $order['dou_code'] != '' || $order['tuan_id'] != -1) {

            $orderAmount = 0;
            $amount = $order['amount'];
            $pay_amount = 0;
        } else {
            $amount = get_charge($start, $hour, $slots, $minute);
            if ($amount <= $table['min_amount']) {
                $amount = $table['min_amount'];

            }

            if ($amount > $order['ya_amount'] && $order['pay_amount'] > 0) {
                $amount = $order['ya_amount'];//先暂时这样处理
            }
            $orderAmount = $amount;

        }

        //1.计算费用
        $tableModel->where('id', $order['table_id'])->update(['status' => 'free']);
        //2.断电

        $mno = $this->mno;
        $refundAmount = 0;
        $dbBalance = 0;


        if ($orderAmount > 0) {

            $userBalanceModel = new Userbalance();

            //如果是余额开台
            if ($order['balance'] > 0 && $order['ya_amount'] == 0) {
                $pay_amount = 0;
                $refundAmount = 0;
                $dbBalance = $amount;
                $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                if ($b) {
                    $userBalanceModel->where('id', $b['id'])->update(['amount' => $dbBalance]);
                }
            } else {
                $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                if ($balance < 0) $balance = 0;
                $shopOrderProfitModel = new Shoporderprofit();
                if ($balance == 0) {
                    //3. 发分润
                    $pay_rate = formatMoney($shop['pay_rate'] * $amount / 100);
                    $rate = formatMoney($shop['ratio'] * $amount / 100);
                    $shopProfit = $amount - $pay_rate - $rate;
                    $refundAmount = $order['ya_amount'] - $amount;
                    $pay_amount = $amount;
                    $dbBalance = 0;
                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                } else {

                    if ($amount <= $balance) {
                        $refundAmount = $order['ya_amount'];
                        $dbBalance = $amount;
                        $pay_amount = 0;
                        error_log("===amount=====" . $amount);
                    } else {
                        $refundAmount = $order['ya_amount'] - ($amount - $balance);
                        $dbBalance = $balance;
                        $dbAmount = $amount - $balance;
                        $pay_amount = $order['ya_amount'] - $refundAmount;

                        $pay_rate = formatMoney($shop['pay_rate'] * $dbAmount / 100);
                        $rate = formatMoney($shop['ratio'] * $dbAmount / 100);
                        $shopProfit = $amount - $pay_rate - $rate;

                        if ($shopProfit > 0) {
                            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                        }

                    }
                    if ($dbBalance > 0) {
                        $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                    }
                }
                //部分退款
                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
                if ($shopMno && $shopMno['ratio'] == 100) {
                    $mno = $shopMno['mno'];
                }
                error_log(formatMoney($refundAmount) . "=====refundAmount==" . $refundAmount);

                $req = array();
                $req['mno'] = $mno;
                $req['ordNo'] = getOrderSn();
                $req['origOrderNo'] = $order['order_no'];
                $req['amt'] = formatMoney($refundAmount);

                if ($refundAmount > 0) {
                    error_log("==refund req===" . json_encode($req));
                    $vbillService = new VbillService();
                    $ret = $vbillService->refund($req);
                    error_log("=====refund=sxf==" . $ret);
                }
            }


        } else {
            //扣余额

            if ($order['dou_code'] != '' || $order['mt_code'] != "") {

            } else {
                $userBalanceModel = new Userbalance();
                $db = array();
                $db['user_id'] = $order['user_id'];
                $db['type'] = "out";
                $db['amount'] = $amount;
                $db['mark'] = $order['shop_name'] . $order['table_name'] . "抵扣";
                $db['create_time'] = time();
                $db['shop_id'] = $order['shop_id'];
                $db['order_id'] = $order['id'];
                $db['b_type'] = "order";
                $db['from'] = "tq";
                $userBalanceModel->insert($db);

            }

        }
        $tableOrderModel->where('id', $order['id'])->update(['book_end' => $book_end, 'amount' => $amount, 'pay_amount' => $pay_amount, 'status' => 'done', 'refund_amount' => $refundAmount, 'is_done' => 1, 'update_time' => time(), 'balance' => $dbBalance]);

        //关闭


        $tableOrderModel->where('id', $order['id'])->update(['update_time' => time()]);

        if ($device['version'] == 1) {
            $req = array();
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];

            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        } else {
            $req['sec'] = 0;
            $req['voice'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        }


        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);


        $this->success('成功');

    }

    public function sum()
    {

        $page = $this->request->param('page');
        $limit = 30;
        $offset = ($page - 1) * $limit;

        $shopModel = new Shop();
        $shopOrderModel = new Shoporder();
        $chargeModel = new Shopcharge();
        $tuanOrderModel = new Tuanorder();
        $list = $shopModel->where('id', 'in', [442])->select();

        $shopTradeModel = new Shopdaytrade();

        $tqTableOrderModel = new Shoptableorder();
        foreach ($list as $key => $val) {

            $book_amount = $shopOrderModel->where('shop_id', $val['id'])->whereTime('create_time', 'yesterday')->where('status', 'not in', ['paying', 'refund'])->sum('amount');
            $book_pay_amount = $shopOrderModel->where('shop_id', $val['id'])->whereTime('create_time', 'yesterday')->where('status', 'not in', ['paying', 'refund'])->sum('pay_amount');
            $charge_amount = $chargeModel->where('shop_id', $val['id'])->whereTime('create_time', 'yesterday')->where('status', 'payed')->sum('amount');
            $tuan_amount = $tuanOrderModel->where('shop_id', $val['id'])->whereTime('create_time', 'yesterday')->where('status', 'payed')->sum('amount');
            $balance_amount = $shopOrderModel->where('shop_id', $val['id'])->whereTime('create_time', 'yesterday')->where('status', 'not in', ['paying', 'refund'])->sum('balance');

            $tq_amount = $tqTableOrderModel->whereTime("create_time", 'today')->where('shop_id', $val['id'])->where('status', 'done')->sum('amount');


            $refund_amount = $shopOrderModel->where('shop_id', $val['id'])->whereTime('create_time', 'yesterday')->where('status', 'refund')->sum('pay_amount');


            $mtCheckTotalAmount = $shopOrderModel->whereTime("create_time", 'yesterday')->where('mt_code', "<>", "")->where('shop_id', $val['id'])->sum('amount');
            $mtCheckPayAmount = $shopOrderModel->whereTime("create_time", 'yesterday')->where('mt_code', "<>", "")->where('shop_id', $val['id'])->sum('pay_amount');

            $douCheckTotalAmount = $shopOrderModel->whereTime("create_time", 'yesterday')->where('dou_code', "<>", "")->where('shop_id', $val['id'])->sum('amount');
            $douCheckPayAmount = $shopOrderModel->whereTime("create_time", 'yesterday')->where('dou_code', "<>", "")->where('shop_id', $val['id'])->sum('pay_amount');


            $mtAmount = $mtCheckTotalAmount - $mtCheckPayAmount;
            $douAmount = $douCheckTotalAmount - $douCheckPayAmount;

            $profit = $book_pay_amount + $charge_amount + $tuan_amount;
            $profit = $profit * $val['ratio'] / 100;

            $db = array();
            $db['shop_id'] = $val['id'];
            $db['org_id'] = $val['org_id'];
            $db['shop_name'] = $val['name'];
            $db['create_time'] = strtotime("-1 day", time());
            $db['book_amount'] = $book_amount;
            $db['book_pay_amount'] = $book_pay_amount;
            $db['charge_amount'] = $charge_amount;
            $db['tuan_amount'] = $tuan_amount;
            $db['dou_amount'] = $douAmount;
            $db['mt_amount'] = $mtAmount;
            $db['profit'] = $profit;
            $db['refund_amount'] = $refund_amount;
            $db['balance_amount'] = $balance_amount;
            $db['tq_amount'] = $tq_amount;
            $db['total_amount'] = $tq_amount + $book_amount;

            if ($book_amount > 0) {
                $shopTradeModel->insert($db);
            }
        }
        $this->success("成功");

    }

    public function testMqtt()
    {

        $id = $this->request->param('id');
        $sec = $this->request->param('sec');


        $cmd = array();
        $header = array();
        $header['Code'] = time();
        $header['Time'] = getMillisecond();
        $header['Sign'] = "lvzaina";

        $body = array();
        $body['MsgId'] = rand(1, 1000000);
        $body['Cmd'] = "Order";
        $body['ID'] = $id;
        $body['Delay'] = intval($sec);
        $body['Type'] = 0;
        $body['DCL'] = 5;

        $cmd['Header'] = $header;
        $cmd['Body'] = $body;

        $msg = json_encode($cmd);
        $option = array();
        $username = 'lvzaina';
        $password = "iot@auth.lvzaina";
        $option['clean_session'] = 1;
        $option['username'] = $username;
        $option['password'] = $password;
        $mqtt = new Client('mqtt://47.97.67.38:1883', $option);
        $mqtt->connect();
        $mqtt->publish('CIOT/2000/HOST/R2F6A76C28', $msg);

        Worker::runAll();

        $this->success('成功');
    }

    public function testS()
    {
        $time = strtotime("15:00");


        $time2 = time();
        if ($time < $time2) {
            $this->success("", "time时间小");

        } else {
            $this->success("", "time时间大");

        }


    }

    public function testAir()
    {
        $airService = new AirService();
        $airService->airCheck(466);

        $this->success('成功');
    }

    public function addCode()
    {

        $shop_id = 466;
        $price = 500;
        $chargeCodeModel = new Chargecode();
        for ($i = 0; $i <= 10; $i++) {
            $randomNumber = mt_rand(1000000000, 9999999999);
            $chargeCode = $chargeCodeModel->where('code', $randomNumber)->find();
            if (!$chargeCode) {
                $chargeCodeModel->insert(['shop_id' => 466, 'price' => 500, 'code' => $randomNumber]);
            }
        }
        $this->success('成功');
    }

    public function testMtCode()
    {

        $code = "242210029980429";

        $this->success('', strlen($code));
    }

    public function testTqCall()
    {

        $order_no = "24080622312398575156955469";
        $shopTableOrderModel = new Shoptableorder();
        $order = $shopTableOrderModel->where('order_no', $order_no)->find();
        if ($order) {


            $db = array();
            $db['status'] = "done";
            $db['book_end'] = time();
            $db['is_done'] = 1;
            //抖音核销
            //美团核销
            //团购券
            //在线支付
            if ($order['ya_amount'] > 0 || $order['balance'] > 0) {
                $amount = $order['ya_amount'] + $order['balance'];
                if ($order['ya_amount'] > 0) {
                    $payAmount = $order['ya_amount'];
                }
                $db['amount'] = $amount;
                $db['pay_amount'] = $payAmount;


                if ($order['ya_amount'] > 0) {
                    $userBalanceModel = new Userbalance();
                    $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                    if ($balance > 0) {
                        $db['pay_amount'] = $order['pay_amount'] - $balance;
                        $db['refund_amount'] = $balance;
                        $db['update_time'] = time();

                    }
                }
            }
            //在线支付+余额
            $shopTableOrderModel->where('id', $order['id'])->update($db);
            $shopModel = new Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();
            //发放分润
            if ($db['pay_amount'] > 0) {
                $pay_rate = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
                $rate = formatMoney($shop['ratio'] * $db['pay_amount'] / 100);

                $profit = $db['pay_amount'] - $pay_rate - $rate;
                if ($profit > 0) {
                    $shopOrderProfitModel = new Shoporderprofit();
                    if ($profit > 0) {
                        $shopOrderProfitModel = new Shoporderprofit();
                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($profit)]);
                    }
                }
            }

        }
        $this->success('成功');

    }

    public function sendWx()
    {


        $orgModel = new Org();
        $org = $orgModel->where('id', 27)->find();
        if (!$org) $this->error("该号没开通,请联系技术");
        $config = [
            'app_id' => $org['app_id'],
            'secret' => $org['app_secret'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $app = Factory::miniProgram($config);


        $data = [
            'template_id' => 'PKGHDClIKC1gIowLVzy9wi_POF1sT8kz9WNM5sP1NSw', // 所需下发的订阅模板id
            'touser' => 'onT895Q9BD70ZJUvFMdfaRGEYJJ0',     // 接收者（用户）的 openid
            'page' => 'pages/home/index2',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'thing3' => [
                    'value' => '预约科目',
                ],
                'thing2' => [
                    'value' => '缺席店',
                ],
                'date6' => [
                    'value' => '2024-09-20 12:10',
                ],
                'thing9' => [
                    'value' => '王昕峰',
                ],
                'phone_number13' => [
                    'value' => '18201753497',
                ],
            ],
        ];

        $ret = $app->subscribe_message->send($data);

        $this->success('', $ret);


    }

    public function testAgentFee()
    {

        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', "24100820283010110249334639")->find();


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();


        /**
         * 代理商分润
         */
        if ($shop['agent_ratio'] > 0) {

            $userOrderProfitModel = new Userorderprofit();

            $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;

            if ($agentFee > 0) {
                $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                    'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
            }

        }
        $this->success('成功', $shop);
    }

    public function over()
    {

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();

        $from = $this->request->param('from');

        if ($order['status'] == 'done') {

            $this->error("此订单此完成 无需操作");
        }

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $order['table_id'])->find();
        if ($order['book_end'] == -1) {
            if ($from != 'task') {
                if (($order['is_qiu'] == -1 || $order['is_lock'] == -1) && $device['is_weight'] == 1) {

                    $this->error("", "", "2");
                }
            }
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();
            $rule = json_decode($table['rule'], true);
            $book_end = time();
            $minute = floor(($book_end - $order['book_start']) % 86400 / 60);
            $hour = ceil($minute / 60);
            $start = date("H", $order['book_start']);


            $time1List = explode("~", $rule['time1']);
            if (count($time1List) == 1) {
                $startTime1 = explode("-", $rule['time1'])[0];
                $endTime1 = explode("-", $rule['time1'])[1];
            } else {
                $startTime1 = explode("~", $rule['time1'])[0];
                $endTime1 = explode("~", $rule['time1'])[1];
            }

            $time2List = explode("~", $rule['time2']);
            if (count($time2List) == 1) {
                $startTime2 = explode("-", $rule['time2'])[0];
                $endTime2 = explode("-", $rule['time2'])[1];
            } else {
                $startTime2 = explode("~", $rule['time2'])[0];
                $endTime2 = explode("~", $rule['time2'])[1];
            }


            $startTime1 = intval($startTime1);
            $endTime1 = intval($endTime1);


            $startTime2 = intval($startTime2);
            $endTime2 = intval($endTime2);
            $slots = array();

            if ($endTime1 < $startTime1) {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
            }

            if ($endTime2 < $startTime2) {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
            }

            $hour = floor($minute / 60);

            $orderAmount = $order['pay_amount'];
            $pay_amount = 0;
            if ($order['mt_code'] != '' || $order['dou_code'] != '' || $order['tuan_id'] != -1) {

                $orderAmount = 0;
                $amount = $order['amount'];
                $pay_amount = 0;
            } else {
                $amount = get_charge($start, $hour, $slots, $minute);
                if ($amount <= $table['min_amount']) {
                    $amount = $table['min_amount'];
                }
                if ($amount > $order['ya_amount'] && $order['pay_amount'] > 0) {
                    $amount = $order['ya_amount'];//先暂时这样处理
                }
                $orderAmount = $amount;

            }
            //1.计算费用
            //2.断电
            $mno = $this->mno;
            $refundAmount = 0;
            $dbBalance = 0;


            if ($orderAmount > 0) {

                $userBalanceModel = new Userbalance();

                //如果是余额开台
                if ($order['balance'] > 0 && $order['ya_amount'] == 0) {
                    $pay_amount = 0;
                    $refundAmount = 0;
                    $dbBalance = $amount;
                    $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                    if ($b) {
                        // $userBalanceModel->where('id', $b['id'])->update(['amount' => $dbBalance]);
                    }
                } else {
                    $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                    if ($balance < 0) $balance = 0;
                    $shopOrderProfitModel = new Shoporderprofit();
                    if ($balance == 0) {
                        //3. 发分润
                        $pay_rate = formatMoney($shop['pay_rate'] * $amount / 100);
                        $rate = formatMoney($shop['ratio'] * $amount / 100);
                        $shopProfit = $amount - $pay_rate - $rate;
                        $refundAmount = $order['ya_amount'] - $amount;
                        $pay_amount = $amount;
                        $dbBalance = 0;
//                            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
//                                'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                    } else {

                        if ($amount <= $balance) {
                            $refundAmount = $order['ya_amount'];
                            $dbBalance = $amount;
                            $pay_amount = 0;
                            error_log("===amount=====" . $amount);
                        } else {
                            $refundAmount = $order['ya_amount'] - ($amount - $balance);
                            $dbBalance = $balance;
                            $dbAmount = $amount - $balance;
                            $pay_amount = $order['ya_amount'] - $refundAmount;

                            $pay_rate = formatMoney($shop['pay_rate'] * $dbAmount / 100);
                            $rate = formatMoney($shop['ratio'] * $dbAmount / 100);
                            $shopProfit = $amount - $pay_rate - $rate;

//                                if ($shopProfit > 0) {
//                                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
//                                        'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
//                                }

                        }
                        if ($dbBalance > 0) {
                            // $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                        }
                    }
                    //部分退款
                    $shopMnoModel = new Shopmno();
                    $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
                    if ($shopMno && $shopMno['ratio'] == 100) {
                        $mno = $shopMno['mno'];
                    }
                    error_log(formatMoney($refundAmount) . "=====refundAmount==" . $refundAmount);

                    $req = array();
                    $req['mno'] = $mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = formatMoney($refundAmount);

                    if ($refundAmount > 0) {
                        error_log("==refund req===" . json_encode($req));
                        $vbillService = new VbillService();
                        //$ret = $vbillService->refund($req);
                        error_log("=====refund=sxf==" . $ret);
                    }
                }


            } else {
                //扣余额

                if ($order['dou_code'] != '' || $order['mt_code'] != "") {

                } else {
                    $userBalanceModel = new Userbalance();
                    $db = array();
                    $db['user_id'] = $order['user_id'];
                    $db['type'] = "out";
                    $db['amount'] = $amount;
                    $db['mark'] = $order['shop_name'] . $order['table_name'] . "抵扣";
                    $db['create_time'] = time();
                    $db['shop_id'] = $order['shop_id'];
                    $db['order_id'] = $order['id'];
                    $db['b_type'] = "order";
                    $db['from'] = "tq";
                    // $userBalanceModel->insert($db);

                }

            }
            // $tableOrderModel->where('id', $order['id'])->update(['book_end' => $book_end, 'amount' => $amount, 'pay_amount' => $pay_amount, 'status' => 'done', 'refund_amount' => $refundAmount, 'is_done' => 1, 'update_time' => time(), 'balance' => $dbBalance]);

            //关闭
        }
        // $tableOrderModel->where('id', $order['id'])->update(['status' => 'done']);
        // $tableModel->where('id', $order['table_id'])->update(['status' => 'free']);


        $this->success('成功');


    }

    public function checkOrder()
    {

        //error_log("=======checkOrder========".date("Y-m-d H:i:s"));
        $tableOrderModel = new Shoptableorder();
        $list = $tableOrderModel->where('status', 'doing')->order('create_time', 'asc')->limit(50)->select();
        $cmdModel = new Cmdlog();
        $tableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();

        $voiceModel = new Voice();
        foreach ($list as $key => $val) {

            if ($val['book_end'] == -1) {
                $table = $tableModel->where('id', $val['table_id'])->find();
                $rule = json_decode($table['rule'], true);
                $book_end = time();
                $minute = floor(($book_end - $val['book_start']) % 86400 / 60);
                $start = date("H", $val['book_start']);


                $time1Count = explode("~", $rule['time1']);
                $time2Count = explode("~", $rule['time2']);

                if ($time1Count > 1 && $time2Count > 1) {
                    $startTime1 = explode("~", $rule['time1'])[0];
                    $endTime1 = explode("~", $rule['time1'])[1];

                    $startTime2 = explode("~", $rule['time2'])[0];
                    $endTime2 = explode("~", $rule['time2'])[1];


                    $startTime1 = intval($startTime1);
                    $endTime1 = intval($endTime1);


                    $startTime2 = intval($startTime2);
                    $endTime2 = intval($endTime2);
                    $slots = array();

                    if ($endTime1 < $startTime1) {
                        $obj = array();
                        $obj['begin'] = $startTime1;
                        $obj['end'] = 24;
                        $obj['charge'] = $rule['price1'];
                        $slots[] = $obj;
                        $obj = array();
                        $obj['begin'] = 0;
                        $obj['end'] = $endTime1;
                        $obj['charge'] = $rule['price1'];
                        $slots[] = $obj;

                    } else {
                        $obj = array();
                        $obj['begin'] = $startTime1;
                        $obj['end'] = $endTime1;
                        $obj['charge'] = $rule['price1'];
                        $slots[] = $obj;
                    }

                    if ($endTime2 < $startTime2) {
                        $obj = array();
                        $obj['begin'] = $startTime2;
                        $obj['end'] = 24;
                        $obj['charge'] = $rule['price2'];
                        $slots[] = $obj;
                        $obj = array();
                        $obj['begin'] = 0;
                        $obj['end'] = $endTime2;
                        $obj['charge'] = $rule['price2'];
                        $slots[] = $obj;

                    } else {
                        $obj = array();
                        $obj['begin'] = $startTime2;
                        $obj['end'] = $endTime2;
                        $obj['charge'] = $rule['price2'];
                        $slots[] = $obj;
                    }

                    $currentHour = date("H", time());
                    $currentPrice = 0;
                    foreach ($slots as $slot) {
                        if ($slot["begin"] <= $currentHour && $currentHour < $slot["end"]) {
                            $currentPrice = $slot["charge"];
                        }
                    }
                    $hour = floor($minute / 60);

                    $amount = get_charge($start, $hour, $slots, $minute);
                    $price = $currentPrice * 15 / 60;
                    if ($amount + $price >= $val['ya_amount']) {
//                        $msgKey = "table_" . $val['order_no'];
//                        $isCount = $this->redis->get($msgKey);
//                        if (!$isCount) {
//                            $this->redis->set($msgKey, 1, 24 * 60 * 60);
//                            $voice = $voiceModel->where('room_id', $val['table_id'])->find();
//                            if ($voice) {
//                                $cArray = array();
//                                $cArray['cmd'] = "voice";
//                                $cArray['msg'] = $val['table_name'] . "台只剩下不足15分钟，请尽快续费";
//                                $pubRequest = new PubRequest([
//                                    "productKey" => "ggy1jAcSplM",
//                                    "topicFullName" => "/ggy1jAcSplM/" . "FPD80000101935" . "/user/get",
//                                    "messageContent" => base64_encode(json_encode($cArray)),
//                                    "iotInstanceId" => "iot-06z00htbh8lvvfe"
//
//                                ]);
//                                $resp = $this->client->pub($pubRequest);
//                            }
//                        }
                    }

                    if ($val['mt_code'] != '' || $val['dou_code'] != '') {
                        if ($val['book_end'] < time()) {
                            $url = "https://app.quexiaqp.com/api/app/shoptable/overOrder";
                            $req = array();
                            $req['order_no'] = $val['order_no'];
                            $req['from'] = "task";
                            echo "=====4===";

                            //Http::post($url, $req);
                        }
                    } else {
                        if ($amount >= $val['ya_amount'] && $val['ya_amount'] != 0) {
                            error_log("===需要续费===" . $val['order_no']);
                            $url = "https://app.quexiaqp.com/api/app/shoptable/overOrder";
                            $req = array();
                            $req['order_no'] = $val['order_no'];
                            $req['from'] = "task";
                            echo "=====3===";

                            //Http::post($url, $req);
                        } else if ($amount >= $val['balance'] && $val['balance'] != 0) {
                            $url = "https://app.quexiaqp.com/api/app/shoptable/overOrder";
                            $req = array();
                            $req['order_no'] = $val['order_no'];
                            $req['from'] = "task";
                            echo "=====2===";

                            //Http::post($url, $req);
                        }
                    }

                }
            } else {
                echo $val['book_end'];
                if ($val['book_end'] < time()) {
                    $url = "https://app.quexiaqp.com/api/app/shoptable/overOrder";
                    $req = array();
                    $req['order_no'] = $val['order_no'];
                    $req['from'] = "task";

                    echo "=====1===";
                    //Http::post($url, $req);
                }
            }


        }
        $this->success("", $list);
    }

    public function queryKd()
    {

        $kdService = new KdService();
        $param = array();
        $param['kd_num'] = "YT8714207586292";
        $ret = $kdService->queryKd($param);
        if ($ret['code'] == 1) {
            $data = json_decode($ret['data'], true);


            $status = $data['status'];
            if ($status == 0) {
                $this->success('', $data['result']['list']);

            } else {
                $this->error($data['msg']);
            }
        } else {
            $this->error($ret['msg']);
        }
    }




    public function syncOrder()
    {
        $id = 19;
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('id',$id)->find();
        if(!$order){
            $this->error("订单不存在");
        }
        $roomModel = new Shoproom();
        $room = $roomModel->where('id',$order['room_id'])->find();
        if($room['mai_id'] != -1){

            $shopModel = new Shop();
            $shop = $shopModel->where('id',$room['shop_id'])->find();
            $orderBookModel = new Shoproombook();
            $book = $orderBookModel->where('order_id',$order['id'])->find();

            $userModel = new \app\admin\model\User();
            $user = $userModel->where('id',$book['user_id'])->find();

            $cleanRoomModel = new Roomclean();
            $clean = $cleanRoomModel->where('order_id',$order['id'])->find();

            $ret = array();
            $ret['shop_id'] =$shop['mai_id'];
            $ret['room_id'] = $room['mai_id'];
            $ret['mobile'] = $user['mobile'];
            $ret['order'] = $order;
            $ret['book'] = $book;
            $ret['clean'] = $clean;

            $url = "https://app.quexiaqp.com/api/app/sync/order";

            Http::post($url, $ret);

        }
    }

}

